/**
 * 15-600: Java and J2EE
 * Instructor: Jeff Eppinger
 * Done By:	Mohammad al Khani
 * Date Dec 10, 2011
 */

package controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.BookmarkDAO;
import model.Model;
import model.UserDAO;
import dataBeans.User;

public class Controller extends HttpServlet{
	private static final long serialVersionUID = 1L;
    
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Controller() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void init() throws ServletException{
    	   Model model = new Model(getServletConfig());
    	   Action.add(new LoginAction(model));
    	   Action.add(new PublicBookmarkAction(model));
    	   Action.add(new RegisterAction(model));
    	   Action.add(new RedirectAction(model));
    	   Action.add(new ManageAction(model));
    	   Action.add(new LogoutAction(model));
    	   Action.add(new AddBookmarkAction(model));
    	   Action.add(new GetUserBookmarksAction(model));
    	   Action.add(new ChangePasswordAction(model));
    	   Action.add(new DeleteBookmarkAction(model));
    	   Action.add(new ManageRedirectAction(model));
    	   
    	   //creating sample users:
    	   try{
    		   UserDAO user = model.getUserDAO();
    		   user.create("Smith", "Jones", "smith.jones@gmail.com", "111");
    		   user.create("Amber", "Davis", "amber.davis@gmail.com", "222");
    		   user.create("Tom", "Harris", "tom.harris@gmail.com", "333");
    		   
    		   User user1 = user.lookup("smith.jones@gmail.com");
    		   User user2 = user.lookup("amber.davis@gmail.com");
    		   User user3 = user.lookup("tom.harris@gmail.com");
    		   
    		   BookmarkDAO bookmarks = model.getBookmarkDAO();
    		   bookmarks.addBookmark(user1.getUserId(), "http://oracle.com", "Oracle corp");
    		   bookmarks.addBookmark(user1.getUserId(), "http://microsoft.com", "Microsoft corp");
    		   bookmarks.addBookmark(user1.getUserId(), "http://google.com", "Google corp");
    		   bookmarks.addBookmark(user1.getUserId(), "http://facebook.com", "Facebook corp");
    		   
    		   bookmarks.addBookmark(user2.getUserId(), "http://ebay.com", "eBay corp");
    		   bookmarks.addBookmark(user2.getUserId(), "http://amazon.com", "Amazon corp");
    		   bookmarks.addBookmark(user2.getUserId(), "http://cmu.edu", "Carnegie Mellon University");
    		   bookmarks.addBookmark(user2.getUserId(), "http://youtube.com", "Youtube corp");
    		   
    		   bookmarks.addBookmark(user3.getUserId(), "http://apple.com", "Apple corp");
    		   bookmarks.addBookmark(user3.getUserId(), "http://dell.com", "Dell corp");
    		   bookmarks.addBookmark(user3.getUserId(), "http://ubuntu.com", "Linux Ubuntu");
    		   bookmarks.addBookmark(user3.getUserId(), "http://hotmail.com", "Hotmail");
    		   
    	   }catch(Exception e){
    		   e.printStackTrace();
    		   System.out.println("Couldn't add sample users");
    	   }
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getAttribute("test") != null){
			System.out.println("test: " + request.getAttribute("test"));
		}
		try{
			if(request.getSession().getAttribute("userList") == null){
				UserDAO userList = new UserDAO();
				request.setAttribute("userList", userList.getUserList());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		String nextPage = performTheAction(request);
		//System.out.println("next page: " + nextPage);
        sendToNextPage(nextPage,request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		  doGet(request,response);
	}
	
	 /*
     * Extracts the requested action and (depending on whether the user is logged in)
     * perform it (or make the user login).
     * @param request
     * @return the next page (the view)
     */
    private String performTheAction(HttpServletRequest request) {
        HttpSession session     = request.getSession(true);
        String      servletPath = request.getServletPath();
        User        user = (User) session.getAttribute("user");
        String      action = getActionName(servletPath);

        System.out.println("servletPath="+servletPath+" requestURI="+request.getRequestURI());

        if (action.equals("register.do") || action.equals("login.do") || action.contains("getUserBookmarks.do")) {
        	// Allow these actions without logging in
			return Action.perform(action,request);
        }
        
        if(action.equals("redirect.do")){
        	return Action.perform("redirect.do",request);
        }
        
        if (user == null) {
        	// If the user hasn't logged in, direct him to the login page
        	return Action.perform("publicBookmark.do",request);
        }
      	// Let the logged in user run his chosen action
		return Action.perform(action,request);
    }
    
    /*
     * If nextPage is null, send back 404
     * If nextPage starts with a '/', redirect to this page.
     *    In this case, the page must be the whole servlet path including the webapp name
     * Otherwise dispatch to the page (the view)
     *    This is the common case
     * Note: If nextPage equals "image", we will dispatch to /image.  In the web.xml file, "/image"
     *    is mapped to the ImageServlet will which return the image bytes for display.
     */
    private void sendToNextPage(String nextPage, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    	System.out.println("nextPage="+nextPage);
    	
    	if (nextPage == null && request.getAttribute("redirectURL") == null) {
    		response.sendError(HttpServletResponse.SC_NOT_FOUND,request.getServletPath());
    		return;
    	}
    	
    	if (nextPage != null && request.getAttribute("redirectURL") != null) {
    		String location = (String)request.getAttribute("redirectURL");
    		if(location.startsWith("http://") == true){
    			response.sendRedirect(location);
    		}else{
    			response.sendRedirect("http://" + location);
    		}
    		return;
    	}
    	
    	if (nextPage.charAt(0) == '/') {
			String host  = request.getServerName();
			String port  = ":"+String.valueOf(request.getServerPort());
			if (port.equals(":80")) port = "";
			//System.out.println("here we are heading to: 	http://"+host+port+nextPage);
			response.sendRedirect("http://"+host+port+nextPage);
			return;
    	}
    	
   		RequestDispatcher d = request.getRequestDispatcher("/"+nextPage);
   		d.forward(request,response);
    }

	/*
	 * Returns the path component after the last slash removing any "extension"
	 * if present.
	 */
    private String getActionName(String path) {
    	// We're guaranteed that the path will start with a slash
        int slash = path.lastIndexOf('/');
        return path.substring(slash+1);
    }
}
